﻿using System;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Collections;

namespace Remind.DBUtility
{
    /// <summary>
    /// access数据库访问对象
    /// </summary>
    public abstract class AccessHelper
    {
        public static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Contacts"].ConnectionString + ConfigurationManager.AppSettings["database"] + "';Jet OLEDB:Database Password=283713763@qq.com;";
        /// <summary>
        /// 哈希表来存储缓存的参数
        /// </summary>
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
        /// <summary>
        /// 执行不返回结果集的Command,对数据库使用提供的参数中指定的连接字符串
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">sql语句</param>
        /// <param name="parms">参数</param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParameters)
        {
            OleDbCommand oleDbCommand = new OleDbCommand();
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                conn.Open();
                PrepareCommand(oleDbCommand, conn, null, cmdType, cmdText, commandParameters);
                try
                {
                    int val = oleDbCommand.ExecuteNonQuery();
                    oleDbCommand.Parameters.Clear();
                    return val;
                }
                catch (InvalidOperationException)
                {
                    return 0;
                }
            }
        }

        /// <summary>
        /// 执行不返回结果集的sqlCommand,对数据库使用提供的参数中的连接对象
        /// </summary>
        /// <param name="conn">连接对象</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">sql语句</param>
        /// <param name="commandParmeters">sql参数</param>
        /// <returns></returns>
        public static int ExecuteNonQuery(OleDbConnection conn, CommandType cmdType, string cmdText, params OleDbParameter[] commandParmeters)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParmeters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();//清除参数
            return val;
        }

        /// <summary>
        /// 执行不返回结果集的Command,对数据库使用提供的参数中的事务连接对象
        /// </summary>
        /// <param name="trans">事务对象</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">sql命令</param>
        /// <param name="commandParmeters">sql参数</param>
        /// <returns>影响行数</returns>
        public static int ExecuteNonQuery(OleDbTransaction trans, CommandType cmdType, string cmdText, params OleDbParameter[] commandParmeters)
        {
            OleDbCommand cmd = new OleDbCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParmeters);
                int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行返回数据集的Command
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">sql命令</param>
        /// <param name="commandParmeters">sql参数</param>
        /// <returns>结果集的datareader</returns>
        public static OleDbDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParmeters)
        {
            OleDbCommand cmd = new OleDbCommand();
            OleDbConnection conn = new OleDbConnection(connectionString);
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParmeters);
                OleDbDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch (OleDbException e)
            {
                conn.Close();
                throw;
            }
            //using (OleDbConnection conn = new OleDbConnection(connectionString))
            //{Provider=Microsoft.Jet.OLEDB.4.0;Data Source="D:\My Documents\Visual Studio 2008\Projects\Remind\Remind\联系人.mdb";Persist Security Info=True
            //Provider=Microsoft.Jet.OLEDB.4.0;Data Source="D:\My Documents\Visual Studio 2008\Projects\Remind\Remind\联系人.mdb"
            //    try
            //    {
            //        PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParmeters);
            //        OleDbDataReader rdr = cmd.ExecuteReader();
            //        cmd.Parameters.Clear();
            //        return rdr;
            //    }
            //    catch
            //    {
            //        conn.Close();
            //        throw;
            //    }
            //}
        }

        /// <summary>
        /// 执行返回一条记录的command
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="cmdType">连接类型</param>
        /// <param name="cmdText">sql命令</param>
        /// <param name="commandParmeters">sql参数</param>
        /// <returns>首行首列</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params OleDbParameter[] commandParmeters)
        {
            OleDbCommand cmd = new OleDbCommand();
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParmeters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// 参数数组添加到缓存
        /// </summary>
        /// <param name="cachekey">参数缓存的关键字</param>
        /// <param name="commandParmeters">缓存sqlparamters的数组</param>
        public static void CacheParameters(string cachekey, params OleDbParameter[] commandParmeters)
        {
            parmCache[cachekey] = commandParmeters;
        }

        /// <summary>
        /// 读取缓存参数
        /// </summary>
        /// <param name="cachekey">用于查找的键参数</param>
        /// <returns>缓存的参数数组</returns>
        public static OleDbParameter[] GetCacheParmeters(string cachekey)
        {
            OleDbParameter[] cacheParmeters = (OleDbParameter[])parmCache[cachekey];
            if (cachekey == null)
                return null;
            OleDbParameter[] clonedParms = new OleDbParameter[cacheParmeters.Length];
            for (int i = 0, j = clonedParms.Length; i < j; i++)
            {
                clonedParms[i] = (OleDbParameter)((ICloneable)clonedParms[i]).Clone();
            }
            return clonedParms;
        }
        /// <summary>
        /// 准备用于执行的命令
        /// </summary>
        /// <param name="cmd">sql命令</param>
        /// <param name="conn">连接对象</param>
        /// <param name="trans">事务</param>
        /// <param name="cmdType">连接类型</param>
        /// <param name="cmdText">命令语句</param>
        /// <param name="cmdParms">命令参数数组</param>
        private static void PrepareCommand(OleDbCommand cmd, OleDbConnection conn, OleDbTransaction trans, CommandType cmdType, string cmdText, OleDbParameter[] cmdParms)
        {
            
            //检查状态
            if (conn.State != ConnectionState.Open)
                conn.Open();

            //设置命令连接对象
            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            //事务是否为空
            if (trans != null)
                cmd.Transaction = trans;

            //设置命令类型
            cmd.CommandType = cmdType;
            if (cmdParms != null)
                foreach (OleDbParameter item in cmdParms)
                {
                    cmd.Parameters.Add(item);
                }
        }
    }
}
